<script lang="ts" setup>
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { h, onMounted, onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Input, message, Popconfirm, Space, Spin, Switch } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getSupplyList } from '#/api/common'
import {payOrderAgainst, payOrderApproval, payOrderDel, payOrderList} from '#/api/payOrder'
import { againstSupply, approvalSupply, delSupply, editSupply, getContractList, SupplyExcel } from '#/api/supply'

import popupForm from './popupForm.vue'

const keyword4 = ref('')
const fetching = ref(false)
// 计算六个月前的日期
const today = new Date()
const sixMonthsAgo = new Date()
sixMonthsAgo.setMonth(today.getMonth() - 6)
// 格式化日期为YYYY-MM-DD
const formatDate = (date, isEndDate = false) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const time = isEndDate ? '23:59:59' : '00:00:00'
  return `${year}-${month}-${day} ${time}`
}
async function fetchgetSupplyIndex({ keyword = '' }: Record<string, any>) {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const searchValue = ref()
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'record_sn',
      label: '付款单号',
      operator: '=',
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'record_date',
      operator: 'RANGE',
      defaultValue: [formatDate(sixMonthsAgo), formatDate(today, true)],
      label: '付款日期',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchgetSupplyIndex,
          // 禁止本地过滤
          filterOption: false,
          mode: 'multiple',
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword4.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword4.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'supply_id',
      operator: 'IN',
      label: '供应商',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
    trigger: 'row',
  },

  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    { title: '调整单号', field: 'record_sn', align: 'center', sortable: false },
    { title: '调整日期', field: 'record_date', align: 'center', clearable: false },
    { title: '手工单号', field: 'Manualid', align: 'center', sortable: false },
    {
      title: '供应商',
      field: 'supply',
      align: 'center',
      width:  200,
      slots: { default: 'supply' }
    },
    { title: '项目', field: 'Item', align: 'center', sortable: false },
    { title: '付款方式', field: 'Fkmode', align: 'center', sortable: false },
    { title: '类别', field: 'FkCategory', align: 'center', sortable: false },
    { title: '金额', field: 'Amount', align: 'center', sortable: false },
    { title: '抵扣定金', field: 'AmountDj', align: 'center', sortable: false },
    { title: '账户名称', field: 'Accountid2', align: 'center', sortable: false },
    { title: '收款人', field: 'Shoukuanren', align: 'center', sortable: false },
    { title: '录入日期', field: 'InputDate', align: 'center', width: 150, sortable: false },
    { title: '操作人', field: 'Operator', align: 'center', sortable: false },
    {
      title: '审核状态',
      field: 'Posted',
      align: 'center',

      cellRender: {
        name: 'CellTag',
        options: [
          { color: 'success', label: '已审核', value: 1 },
          { color: 'error', label: '未审核', value: 0 },
        ],
      },

      sortable: false,
    },
    { title: '审核日期', field: 'PostedDate', align: 'center', width: 150, sortable: false },
    { title: '审核人', field: 'PostUser', align: 'center', sortable: false },
    { title: '备注', field: 'Remark', align: 'center', width: 300, sortable: false },
    // { title: '单据类型', field: 'fktype', show: false, align: 'center',sortable: false },
    { title: '操作', field: 'action', fixed: 'right', slots: { default: 'action' } },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const search: any[] = []
        for (const [key, value] of Object.entries(formValues)) {
          if (value === null || value === '' || value === undefined) continue
          const fieldSchema = formOptions.schema.find((i: any) => i.fieldName === key)
          // 处理特殊字段格式
          let fieldValue = value
          if (key === 'record_date') {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }
          search.push({
            field: key,
            val: fieldValue,
            operator: fieldSchema?.operator,
            render: fieldSchema?.render,
          })
        }
        const res = await payOrderList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          params: {
            'pay_order.fktype': 2
          },
        })
        // 将接口返回的1/0转换为布尔值
        res.list.forEach((row) => {
          row.Istaxrate = row.Istaxrate === 1
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },

  id: 'payCostOrder',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },

}

// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row, 'edit')
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

//  按钮的禁用状态
const isDisabled = ref(true)

const isApprovalDisabled = ref(true)
const isDeleteDisabled = ref(true)

// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
      const hasApprovalCondition = selectedRecords.some(
        (post) =>
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == null) || // 单据
          post.Posted == 0 ||
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == 0) ||
          (post.posted !== undefined && post.posted == 0) ||
          (post.state !== undefined && post.state == 10),
      )

      isApprovalDisabled.value = !hasApprovalCondition

      // 删除按钮禁用逻辑 - 示例逻辑，需根据实际业务规则调整
      isDeleteDisabled.value = !selectedRecords || selectedRecords.length === 0 || !hasApprovalCondition
    } else {
      isDisabled.value = true
      isApprovalDisabled.value = true
      isDeleteDisabled.value = true
    }
  } catch {
    isDisabled.value = true
    isApprovalDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

// 删除
function delRow() {
  const data = gridApi.grid.getCheckboxRecords()
  payOrderDel({ ids: data.map((item) => item.record_sn) }).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
      gridApi.reload()
    }
  })
}
// 审核
function approvalBut() {
  const data = gridApi.grid.getCheckboxRecords()

  const ids = data.map((record: any) => record.record_sn)
  payOrderApproval({ ids }).then((res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    gridApi.reload()
    message.success('审核成功')
  })
}

function againstShow() {
  const data = gridApi.grid.getCheckboxRecords()
  let is_have_Posted_data = false
  data.forEach((item, index) => {
    if (item.Posted == 0) {
      is_have_Posted_data = true
    }
  })
  if (is_have_Posted_data) {
    message.error('存在未审核的数据，无法反审')
    return false
  } else {
    const data = gridApi.grid.getCheckboxRecords()
    payOrderAgainst({ ids: data.map((item) => item.record_sn) }).then((res: any) => {
      if (res.data.code === 0) {
        message.error(res.data.msg)
      } else {
        message.success(res.data.msg)
        gridApi.reload()
      }
    })
  }
}

function modelClose() {
  gridApi.reload()
}

const [formModal, formModalApi] = useVbenModal({
  connectedComponent: popupForm,
})
// 编辑
function openEdit(res: any, but: any) {
  formModalApi.setData({ rowData: res, view: but }).open()
}


const contractList = ref({})
onMounted(() => {
  getContractList().then((res: any) => {
    // 确保contractList是一个对象，根据API返回格式提取正确的数据
    contractList.value = res || {}
  })
})


</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Popconfirm title="删除选中行" ok-text="确认" cancel-text="取消" @confirm="delRow()">
              <Button type="primary" danger title="删除选中行" :disabled="isDeleteDisabled"> 删除 </Button>
            </Popconfirm>
            <template v-if="!isApprovalDisabled">
              <Popconfirm title="确定审核选中记录" ok-text="确认" cancel-text="取消" @confirm="approvalBut()">
                <Button type="primary" class="my-green-btn" title="审核选中行" :disabled="isApprovalDisabled"> 审核 </Button>
              </Popconfirm>
            </template>
            <template v-else>
              <Button type="primary" title="审核选中行" disabled> 审核 </Button>
            </template>
            <Button type="primary" danger :disabled="isDisabled" @click="againstShow()"> 反审 </Button>
          </Space>
        </div>
      </template>

      <!-- 操作列插槽 -->
      <template #supply="{ row }">
        <div>{{ row.supply.SupplyCode+"/"+row.supply.SupplyNa }}</div>
      </template>


      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row, 'edit')"> 编辑 </Button>
        </Space>
      </template>
    </Grid>
    <formModal @refresh="modelClose()" />
    <fileManageModal @close="modelClose()" />
    <exportModal @refresh="modelClose()" />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
